/** 
*
* @author  jiwf 
* @date 创建时间：2016年10月22日 下午4:41:28 
* @version 1.0 
* @since  
*  
*/
package com.xbstar.web;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.sql.DataSource;

import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.xbstar.bean.RouteInfo;
import com.xbstar.bean.UserOrder;
import com.xbstar.dao.OrderRepository;
import com.xbstar.dao.RouteInfoRepository;
import com.xbstar.tools.BeanUtils;
import com.xbstar.tools.Timer;

@RestController
@CrossOrigin
@RequestMapping("/order")
public class OrderController {
	@Autowired
    DataSource dataSource;
	@Autowired
	OrderRepository orderRe;
	@Autowired
	RouteInfoRepository routeRe;
	@RequestMapping("/getall")
	String getAllOrder(){
		JSONObject json=new JSONObject();
		JSONArray array=new JSONArray();
		  try {
			Connection conn  = dataSource.getConnection();
			 String sqlString="SELECT orderId,bookTime,endTime,startTime,cost,routeInfoId,state,userName,nickName,userId,routeName,routeDescription from userrouteoderview";
			 PreparedStatement ps = conn.prepareStatement(sqlString);
			 ResultSet rs = ps.executeQuery();
			 while (rs.next()) {
				 JSONObject tjson=new JSONObject();
				 tjson.put("orderId", rs.getString("orderId"));
				 tjson.put("bookTime", rs.getString("bookTime"));
				 tjson.put("endTime", rs.getString("endTime"));
				 tjson.put("startTime", rs.getString("startTime"));
				 tjson.put("cost", rs.getString("cost"));
				 tjson.put("routeInfoId", rs.getString("routeInfoId"));
				 tjson.put("state", rs.getString("state"));
				 tjson.put("userName", rs.getString("userName"));
				 tjson.put("nickName", rs.getString("nickName"));
				 tjson.put("userId", rs.getString("userId"));
				 tjson.put("routeDescription", rs.getString("routeDescription"));
				 tjson.put("routeName", rs.getString("routeName"));
				 array.put(tjson);
			 }
			 json.put(UserPackage.STATUS, UserPackage.SUCCESS);
			 json.put(UserPackage.DATA, array);
			 rs.close();
			 ps.close();
			 conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
			json.put(UserPackage.STATUS, UserPackage.SERVER_ERROR);
		}
		 
		return json.toString();
	}
	@RequestMapping("/add")
	String addOrder(@RequestParam("userId") Long userId,@RequestParam("routeInfoId")Long routeInfoId,HttpServletRequest req){
		JSONObject json=new JSONObject();
		UserOrder order=new UserOrder();
		try {
			order=BeanUtils.copyRequestToObj(order, req);
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		order.setState("0");
		order.setRouteInfoId(routeInfoId);
		RouteInfo route=routeRe.findOne(routeInfoId);
		if(route==null){
			json.put(UserPackage.STATUS, UserPackage.EMPTY);
			return json.toString();
		}
		order.setCost(route.getCost().toString());
		order.setUserId(userId);
		order.setBookTime(Timer.getCurrentString());
		try {
			List<UserOrder>orlist=orderRe.findHaveOrder(routeInfoId, userId, order.getStartTime(), order.getEndTime());
			boolean flag=false;
			for (UserOrder userOrder : orlist) {
				if(!"4".equals(userOrder.getState())){
					flag=true;
					break;
				}
			}
			if(orlist.size()>0&&flag==true){
				json.put(UserPackage.STATUS, UserPackage.REDO);
				return json.toString();
			}
			order=orderRe.save(order);
			json.put(UserPackage.STATUS, UserPackage.SUCCESS);
			json.put(UserPackage.DATA, BeanUtils.getAJsonFromObj(order, null));
		} catch (Exception e) {
			e.printStackTrace();
			json.put(UserPackage.STATUS, UserPackage.SERVER_ERROR);
		}
		return json.toString();
	}
	@RequestMapping("/edit")
	public  String editOrder(@RequestParam("id")Long orderId,@RequestParam("state")String state){
		JSONObject json=new JSONObject();
		UserOrder order=new UserOrder();
//		if(!state.equals("1")){
//			json.put(UserPackage.STATUS, UserPackage.ERR_PARAM);
//			return json.toString();
//		}
		try {
			order=orderRe.findOne(orderId);
			if(order!=null){
				order.setUpdatedTime(Timer.getCurrentString());
				order.setState(state);
				orderRe.save(order);
				json.put(UserPackage.STATUS, UserPackage.SUCCESS);
			}else{
				json.put(UserPackage.STATUS, UserPackage.EMPTY);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return json.toString();
	}
	@RequestMapping("/del")
    public	String delOrder(@RequestParam("id")Long orderId){
		JSONObject json=new JSONObject();
		try {
			orderRe.delete(orderId);
			json.put(UserPackage.STATUS, UserPackage.SUCCESS);          
		} catch (Exception e) {
			e.printStackTrace();
			json.put(UserPackage.STATUS, UserPackage.EMPTY);
		}
		return json.toString();
	}
	@RequestMapping("getallbyuser")
	public String getOrderByUserId(@RequestParam("userId")Long userId){
		JSONObject json=new JSONObject();
		String sql="SELECT orderId,cost,routeInfoId,routeName,state,nickName,endTime,startTime,userId,bookTime,routeDescription,url FROM userrouteoderview WHERE userId=? ORDER BY state";
		//List<UserOrder> sssd=orderRe.findByUserIdOrderByState(userId);
		JSONArray array=new JSONArray();
		try {
			Connection conn  = dataSource.getConnection();
			 PreparedStatement ps = conn.prepareStatement(sql);
			 ps.setLong(1, userId);
			 ResultSet rs = ps.executeQuery();
			 while (rs.next()) {
				 JSONObject tjson=new JSONObject();
				 if(rs.getString("state").equals("4")){
					 continue;
				 }
				 tjson.put("orderId", rs.getString("orderId"));
				 tjson.put("bookTime", rs.getString("bookTime"));
				 tjson.put("endTime", rs.getString("endTime"));
				 tjson.put("startTime", rs.getString("startTime"));
				 tjson.put("beginTime", rs.getString("startTime"));
				 tjson.put("cost", rs.getString("cost"));
				 tjson.put("routeInfoId", rs.getString("routeInfoId"));
				 tjson.put("state", rs.getString("state"));
				 tjson.put("nickName", rs.getString("nickName"));
				 tjson.put("userId", rs.getString("userId"));
				 tjson.put("url", rs.getString("url"));
				 tjson.put("routeDescription", rs.getString("routeDescription"));
				 tjson.put("routeName", rs.getString("routeName"));
				 String sqla="SELECT cost,tripTime FROM group2grouprelationview WHERE orderId=?";
				 PreparedStatement ps1 = conn.prepareStatement(sqla);
				 ps1.setLong(1, rs.getLong("orderId"));
				 ResultSet rs1 = ps1.executeQuery();
				 if(rs1.next()) {
					 String tripTime=rs1.getString("tripTime");
					 if(tripTime!=null){
						 tjson.put("startTime",tripTime);
					 }
					 tjson.put("cost", rs1.getString("cost"));
				 }
				 rs1.close();
				 ps1.close();
				 array.put(tjson);
			 }
			ps.close();
			rs.close();
			conn.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		json.put("status", "200");
		json.put("data", array);
		return json.toString();
		
	}
	@RequestMapping("getlessbyuser")
	public String getLessOrderByUserId(@RequestParam("userId")Long userId){
		JSONObject json=new JSONObject();
		String sql="SELECT orderId,routeInfoId,routeName,endTime,startTime FROM userrouteoderview WHERE userId=? and state='1'";
		JSONArray array=new JSONArray();
		try {
			Connection conn  = dataSource.getConnection();
			 PreparedStatement ps = conn.prepareStatement(sql);
			 ps.setLong(1, userId);
			 ResultSet rs = ps.executeQuery();
			 while (rs.next()) {
				 JSONObject tjson=new JSONObject();
				 tjson.put("orderId", rs.getString("orderId"));
				 tjson.put("name", rs.getString("routeName"));
				 tjson.put("to", rs.getString("endTime"));
				 tjson.put("from", rs.getString("startTime"));
				 array.put(tjson);
			 }
			 ps.close();
			 rs.close();
			 conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		json.put("data", array);
		json.put("status", "200");
		return json.toString();
		
	}
}
